#include "StudentModifyWidget.h"
#include "ui_StudentModifyWidget.h"
#include <QFormLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QDebug>
#include <QIcon>
#include <QMouseEvent>

StudentModifyWidget::StudentModifyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    if (connectToDatabase())
    {
        loadStudentData(); // 加载学生数据
    }
    setupUI(); // 初始化 UI
}

StudentModifyWidget::~StudentModifyWidget()
{
    delete ui;
}

void StudentModifyWidget::setupUI()
{
    ui->saveButton->setEnabled(false);
    ui->calendarButton->setIcon(QIcon(":/studentimage/calendar_icon.png")); // 设置按钮图标

    connect(ui->calendarButton, &QPushButton::toggled, this, &StudentModifyWidget::on_calendarButton_clicked);
    connect(ui->saveButton, &QPushButton::toggled, this, &StudentModifyWidget::on_saveButton_clicked);
    connect(ui->cancelButton, &QPushButton::clicked, this, &StudentModifyWidget::on_cancelButton_clicked);

    // 连接输入框文本变化信号
    connect(ui->nameEdit, &QLineEdit::textChanged, this, &StudentModifyWidget::checkFormValidity);
    connect(ui->IDEdit, &QLineEdit::textChanged, this, &StudentModifyWidget::checkFormValidity);
    connect(ui->birthDateEdit, &QLineEdit::textChanged, this, &StudentModifyWidget::checkFormValidity);
    connect(ui->phoneEdit, &QLineEdit::textChanged, this, &StudentModifyWidget::checkFormValidity);
    connect(ui->emailEdit, &QLineEdit::textChanged, this, &StudentModifyWidget::checkFormValidity);
}

void StudentModifyWidget::setID(const int &id)
{
    this->id=id;    //获取当前学生id
}

bool StudentModifyWidget::isFieldValid(QLineEdit *field, const QRegularExpression &regex)
{
    return regex.match(field->text()).hasMatch();
}

void StudentModifyWidget::on_cancelButton_clicked()
{
    close();
}

void StudentModifyWidget::checkFormValidity()
{
    // 定义用于验证的正则表达式
    QRegularExpression nameRegex("^[a-zA-Z\u4E00-\u9FA5\\s]+$"); // 中英文字符
    QRegularExpression studentIDRegex("^\\d+$"); // 只允许数字
    QRegularExpression birthDateRegex("^\\d{4}-\\d{2}-\\d{2}$"); // YYYY-MM-DD
    QRegularExpression phoneRegex("^1[3-9]\\d{9}$"); // 标准11位手机号
    QRegularExpression emailRegex("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.com$"); //标准邮箱格式

    //检查所有必填字段是否已填写且有效
    bool isFormValid =
            isFieldValid(ui->nameEdit, nameRegex) &&
            isFieldValid(ui->IDEdit, studentIDRegex) &&
            isFieldValid(ui->birthDateEdit, birthDateRegex) &&
            isFieldValid(ui->phoneEdit, phoneRegex) &&
            isFieldValid(ui->emailEdit, emailRegex);

    // 根据表单有效性启用/禁用保存按钮
    ui->saveButton->setEnabled(isFormValid);
}

void StudentModifyWidget::saveStudentInfo()
{
    QSqlQuery query;
    query.prepare("UPDATE students SET name = :name, birth_date = :birth_date, "
                  "city = :city, residence = :residence, phone = :phone, "
                  "email = :email WHERE student_id = :id");

    query.bindValue(":name", ui->nameEdit->text());
    query.bindValue(":birth_date", ui->birthDateEdit->text());
    query.bindValue(":city", ui->cityEdit->text());
    query.bindValue(":residence", ui->residenceEdit->text());
    query.bindValue(":phone", ui->phoneEdit->text());
    query.bindValue(":email", ui->emailEdit->text());
    query.bindValue(":id", ui->IDEdit->text()); // 根据学号定位学生

    if (query.exec())
    {
        qDebug() << "数据更新成功";
        emit dataSaved(); // 触发数据保存信号
    }
    else
    {
        qDebug() << "更新数据时出错:" << query.lastError().text();
    }
}

void StudentModifyWidget::handleDateSelection(const QDate &date)
{
    // 将选中的日期设置到 QLineEdit 中
    ui->birthDateEdit->setText(date.toString("yyyy-MM-dd"));
    closeCalendar(); // 关闭日历
}

void StudentModifyWidget::closeCalendar()
{
    if (calendar)
    {
        calendar->hide(); // 隐藏日历
        calendar->deleteLater(); // 删除日历控件
        calendar = nullptr; // 置为 nullptr
    }
}

bool StudentModifyWidget::connectToDatabase()
{
    db = QSqlDatabase::addDatabase("QMYSQL"); // 使用 MySQL 驱动
    db.setHostName("192.168.85.128"); // 数据库主机，若使用本机则为 localhost
    db.setDatabaseName("test268"); // 数据库名
    db.setUserName("root"); // 数据库用户名
    db.setPassword("123456"); // 数据库密码

    if (!db.open())
    {
        qDebug() << "无法连接到数据库:" << db.lastError().text();
        return false;
    }
    return true;
}

void StudentModifyWidget::loadStudentData()
{
    QSqlQuery query("SELECT * FROM students WHERE student_id = :id");
    query.bindValue(":id", "学生的学号"); // 根据具体学生的学号查询
    if (query.exec() && query.next())
    {
        ui->nameEdit->setText(query.value("name").toString());
        ui->IDEdit->setText(query.value("student_id").toString());
        ui->birthDateEdit->setText(query.value("birth_date").toString());
        ui->cityEdit->setText(query.value("city").toString());
        ui->residenceEdit->setText(query.value("residence").toString());
        ui->phoneEdit->setText(query.value("phone").toString());
        ui->emailEdit->setText(query.value("email").toString());
        // 根据需求设置只读字段
    }
}

void StudentModifyWidget::on_saveButton_clicked()
{
    saveStudentInfo();
}

void StudentModifyWidget::on_calendarButton_clicked()
{
    //    // 如果日历已经存在，则返回
    //    if (calendar)
    //    {
    //        return;
    //    }

    calendar = new QCalendarWidget(this); // 初始化为成员变量
    calendar->setWindowFlags(Qt::Popup); // 设置为弹出窗口样式
    calendar->move(QCursor::pos()); // 移动到鼠标位置
    calendar->show();

    // 连接日历的 activated 信号到槽函数
    connect(calendar, &QCalendarWidget::activated, this, &StudentModifyWidget::handleDateSelection);

    // 安装事件过滤器
    calendar->installEventFilter(this);
}

// 事件过滤器
bool StudentModifyWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == calendar)
    {
        if (event->type() == QEvent::MouseButtonPress)
        {
            // 鼠标点击事件
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

            // 检查点击是否在日历内
            QPoint pos = mouseEvent->pos();
            if (!calendar->geometry().contains(calendar->mapFromGlobal(QCursor::pos())))
            {
                closeCalendar(); // 点击在外部，关闭日历
                return true; // 处理事件
            }
        }
    }
    else if (event->type() == QEvent::MouseButtonPress)
    {
        // 鼠标点击在其他地方，检查是否关闭日历
        QPoint pos = static_cast<QMouseEvent *>(event)->globalPos();
        if (calendar && !calendar->geometry().contains(pos))
        {
            closeCalendar(); // 点击在外部，关闭日历
            return true; // 处理事件
        }
    }
    return QWidget::eventFilter(obj, event); // 其他事件交给基类处理
}
